package judesart.app.server;

import judesart.app.client.controller.ProfileController;
import judesart.app.domain.Artist;
import judesart.app.domain.User;
import judesart.app.repository.ArtistDAO;
import judesart.app.service.UserService;
import judesart.app.shared.ValidationException;
import judesart.common.bean.ApplicationContextProvider;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ProfileControllerImpl extends RemoteServiceServlet implements
        ProfileController {
    private static final long serialVersionUID = 1L;

    private final static Log LOGGER = LogFactory.getLog(ProfileControllerImpl.class);

    ArtistDAO artistDAO = ApplicationContextProvider.getCtx().getBean(
            ArtistDAO.class);
    UserService userService = ApplicationContextProvider.getCtx().getBean(
            UserService.class);

    @Override
    public Artist createArtist(Artist artist) throws ValidationException {
        User user = userService.getCurrentUser();
        if (user != null) {
            artist.setUserId(user.getId());
        }
        return artistDAO.createArtist(artist);
    }

    @Override
    public Artist getArtist() {
        try {
            User user = userService.getCurrentUser();
            if (user != null) {
                return artistDAO.findArtistByUserId(user.getId());
            }
            return null;
        } catch (Throwable t) {
            t.printStackTrace();
            LOGGER.error("DDDD", t);
            return null;
        }
    }

    @Override
    public Artist updateArtist(Artist artist) throws ValidationException {
        return artistDAO.updateArtist(artist);
    }

    @Override
    public void deletePhotoFromArtist(Long artistId, Long imageId) {
        User user = userService.getCurrentUser();
        if (user != null) {
            Artist artist = artistDAO.findArtistByUserId(user.getId());
            artistDAO.deleteImageFromArtist(artist, imageId);
        }
    }

    @Override
    public Artist findArtistByUserId(Long userId) {
        return artistDAO.findArtistByUserId(userId);
    }
}
